from typing import Any, Generic, Optional, TypeVar, Union
from pydantic import BaseModel

T = TypeVar("T")

class Result(BaseModel, Generic[T]):
    code: int = 200
    msg: str = "success"
    data: Optional[T] = None

    @classmethod
    def ok(cls, data: Optional[T] = None, msg: str = "success") -> "Result[T]":
        """
        返回成功结果，默认code=200，msg可自定义，data可选
        """
        return cls(code=200, msg=msg, data=data)

    @classmethod
    def error(cls, code: int = 500, msg: str = "未知异常，请联系管理员") -> "Result[Any]":
        """
        返回错误结果，默认code=500，msg可自定义
        """
        return cls(code=code, msg=msg, data=None)

    # 链式设置 code
    def set_code(self, code: int) -> "Result[T]":
        self.code = code
        return self

    # 链式设置 msg
    def set_msg(self, msg: str) -> "Result[T]":
        self.msg = msg
        return self

    # 链式设置 data
    def set_data(self, data: T) -> "Result[T]":
        self.data = data
        return self
